package com.tronsis.distribution.fragment.agent;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;

import com.tronsis.distribution.R;
import com.tronsis.distribution.activity.me.agent.AgentExitProcessingDetailActivity;
import com.tronsis.distribution.bean.AskQuitBean;
import com.tronsis.distribution.biz.factory.UpgradeBizFactory;
import com.tronsis.distribution.eventbus.EventMessage;
import com.tronsis.distribution.eventbus.EventTag;
import com.tronsis.distribution.util.CommonUtil;
import com.tronsis.distribution.util.StateUtil;
import com.tronsis.library.adapter.recyclerview.CommonAdapter;
import com.tronsis.library.adapter.recyclerview.MultiItemTypeAdapter;
import com.tronsis.library.adapter.recyclerview.base.ViewHolder;
import com.tronsis.library.adapter.recyclerview.wrapper.LoadMoreWrapper;
import com.tronsis.library.fragment.BaseFragment;
import com.tronsis.library.http.ListBean;
import com.tronsis.library.http.UICallBack;
import com.tronsis.library.util.DateUtil;
import com.tronsis.library.util.DisplayUtil;
import com.tronsis.library.util.StringUtil;
import com.tronsis.library.widget.MyDecoration;
import com.tronsis.library.widget.RecycleViewDivider;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 退出代理处理
 *
 * @author scofield@tronsis.com
 * @date 2019/3/13 15:58
 */
public class AgentExitProcessingFragment extends BaseFragment {

    @BindView(R.id.rv_stock_audit)
    RecyclerView mRvAudit;

    private List<AskQuitBean> mDataList = new ArrayList<>();
    private String mState;
    private int mPage = 1;
    private int mSize = 15;
    private int mTotal;
    private LoadMoreWrapper mLoadMoreWrapper;

    @Override
    protected View onCreateView() {
        View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_agent_exit_processing, null);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initData() {
        initRv();
        Bundle bundle = getArguments();
        if (bundle != null) {
            mState = bundle.getString("state");
            httpGetAskQuitList(mPage, mSize, true);
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventMessage message) {
        switch (message.getTag()) {
            case EventTag.EXIT_AGENT_LIST:
                httpGetAskQuitList(mPage = 1, mSize = 15, true);
                break;
            default:
                break;
        }
    }

    private void initRv() {
        CommonAdapter<AskQuitBean> adapter = new CommonAdapter<AskQuitBean>(getContext(), mDataList, R.layout.item_agent_exit_processing) {
            @Override
            protected void convert(ViewHolder holder, final AskQuitBean askQuitBean, int position) {
                String name = TextUtils.isEmpty(askQuitBean.getUserName()) ? "-" : askQuitBean.getUserName();
                holder.setText(R.id.tv_exit_name, name);
                holder.setText(R.id.tv_time, DateUtil.getDateTimeString(askQuitBean.getStateOn() == null ? askQuitBean.getCreatedOn() : askQuitBean.getStateOn()));
                boolean isClear = askQuitBean.isClear();
                holder.setText(R.id.tv_is_clear, getString(R.string.format_is_clear, isClear ? "是" : "否"));
//                Button btnPay = holder.getView(R.id.btn_pay);
                String clearType = askQuitBean.getClearType();
                if (isClear) {
                    holder.setVisible(R.id.ll_clear, true);
//                    holder.setText(R.id.tv_clear_type, getString(R.string.format_clear_type, StateUtil.getAgentExitClearType(mContext, clearType)));
                    if (StringUtil.isEquals(clearType, StateUtil.AGENT_QUIT_TYPE_DELIVERY)) {
//                        holder.setText(R.id.tv_return_money, getString(R.string.format_pay_money, getString(R.string.format_price, askQuitBean.getMoney())));
//                        btnPay.setText("确认");
//                        if (askQuitBean.getPriceFid() != null && !askQuitBean.isConfirm()) {
//                            holder.setVisible(R.id.ll_pay, true);
//                        } else {
//                            holder.setVisible(R.id.ll_pay, false);
//                        }
//                        if (askQuitBean.getMoney() == 0) {
//                            holder.setVisible(R.id.tv_return_money, false);
//                            holder.setVisible(R.id.ll_pay, false);
//                        }
                        AskQuitBean.ReceiverAddrBean receiverAddr = askQuitBean.getReceiverAddr();
                        if (receiverAddr != null) {
                            holder.setVisible(R.id.ll_address_info, true);
                            holder.setVisible(R.id.tv_label_receive_info, true);
                            holder.setText(R.id.tv_name, receiverAddr.getName());
                            holder.setText(R.id.tv_phone, receiverAddr.getPhone());
                            holder.setText(R.id.tv_address, CommonUtil.getRegionString(receiverAddr.getRegion()) + receiverAddr.getDetail());
                        } else {
                            holder.setVisible(R.id.ll_address_info, false);
                            holder.setVisible(R.id.tv_label_receive_info, false);
                        }

                    } else {
                        holder.setVisible(R.id.ll_address_info, false);
                        holder.setVisible(R.id.tv_label_receive_info, false);
//                        Double total;
//                        BigDecimal goodPriceBd = new BigDecimal(Double.toString(askQuitBean.getStockPrice()));
//                        BigDecimal profitMoneyBd = new BigDecimal(Double.toString(askQuitBean.getMoney()));
//                        if (askQuitBean.getMoney() > askQuitBean.getStockPrice()) {
//                            total = profitMoneyBd.subtract(goodPriceBd).doubleValue();
//                            holder.setText(R.id.tv_return_money, getString(R.string.format_pay_money, getString(R.string.format_price, total)));
//                            btnPay.setText("确认");
//                            if (askQuitBean.getPriceFid() != null && !askQuitBean.isConfirm()) {
//                                holder.setVisible(R.id.ll_pay, true);
//                            } else {
//                                holder.setVisible(R.id.ll_pay, false);
//                            }
//                        } else {
//                            total = goodPriceBd.subtract(profitMoneyBd).doubleValue();
//                            holder.setText(R.id.tv_return_money, getString(R.string.format_return_money, getString(R.string.format_price, total)));
//                            btnPay.setText("付款");
//                            if (askQuitBean.getStockFid() == null) {
//                                holder.setVisible(R.id.ll_pay, true);
//                            } else {
//                                holder.setVisible(R.id.ll_pay, false);
//                            }
//                        }
//                        if (total == 0) {
//                            holder.setVisible(R.id.tv_return_money, false);
//                            holder.setVisible(R.id.ll_pay, false);
//                        }
                    }

                } else {
                    holder.setVisible(R.id.ll_clear, false);
//                    holder.setText(R.id.tv_return_money, getString(R.string.format_pay_money, getString(R.string.format_price, askQuitBean.getMoney())));
//                    btnPay.setText("确认");
//                    if (askQuitBean.getMoney() == 0) {
//                        holder.setVisible(R.id.tv_return_money, false);
//                        holder.setVisible(R.id.ll_pay, false);
//                    }
                }
                Button btnPay = holder.getView(R.id.btn_pay);
                if (StringUtil.isEquals(askQuitBean.getState(), StateUtil.AGENT_EXIT_HANDLE) && StringUtil.isEquals(clearType, StateUtil.AGENT_QUIT_TYPE_RETURN) && askQuitBean.getStockFid() == null) {
                    holder.setVisible(R.id.ll_pay, true);
                } else {
                    holder.setVisible(R.id.ll_pay, false);
                }
//                if (StringUtil.isEquals(askQuitBean.getState(), StateUtil.AGENT_EXIT_VERIFY)) {
//                    holder.setVisible(R.id.ll_pay, false);
//                }

                btnPay.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mContext, AgentExitProcessingDetailActivity.class);
                        intent.putExtra("AskQuitBean", askQuitBean);
                        startActivity(intent);
                    }
                });

            }
        };

        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Intent intent = new Intent(mContext, AgentExitProcessingDetailActivity.class);
                intent.putExtra("AskQuitBean", mDataList.get(position));
                startActivity(intent);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        mLoadMoreWrapper = new LoadMoreWrapper(adapter);
        mLoadMoreWrapper.setLoadMoreView(R.layout.rv_load_more);
        mLoadMoreWrapper.setOnLoadMoreListener(new LoadMoreWrapper.OnLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                if (mDataList.size() % 15 == 0 && mDataList.size() > 0 && mDataList.size() < mTotal) {
                    mPage = (mDataList.size() / 15) + 1;
                    httpGetAskQuitList(mPage, mSize, false);
                }
            }
        });

        int height = DisplayUtil.getInstance(getContext()).dp2px(14);
        int color = Color.parseColor("#F4F4F4");
        RecycleViewDivider decoration = new RecycleViewDivider(getContext(), MyDecoration.VERTICAL_LIST, height, color);
        mRvAudit.addItemDecoration(decoration);
        mRvAudit.setLayoutManager(new LinearLayoutManager(getContext()));
        mRvAudit.setAdapter(mLoadMoreWrapper);
    }

    private void httpGetAskQuitList(int page, int size, final boolean isRefresh) {
        try {
            UpgradeBizFactory.createBiz().askQuits(getActivity(), page, size, mState, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    ListBean listBean = (ListBean) data;
                    mTotal = listBean.getTotal();
                    List<AskQuitBean> list = listBean.getList();
                    if (isRefresh) {
                        mDataList.clear();
                        mDataList.addAll(list);
                    } else {
                        mDataList.addAll(list);
                    }
                    mLoadMoreWrapper.notifyDataSetChanged();
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();

                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }


}
